package com.ruoyi.factorydata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.factorydata.domain.FactoryData;
import com.ruoyi.factorydata.domain.ProductionLineData;
import com.ruoyi.factorydata.domain.StationData;
import com.ruoyi.factorydata.domain.WorkshopData;
import com.ruoyi.factorydata.domain.dto.FactoryDataDTO;
import com.ruoyi.factorydata.domain.vo.FactoryDataVo;
import com.ruoyi.factorydata.domain.vo.FactoryTreeVo;
import com.ruoyi.factorydata.mapper.FactoryDataMapper;
import com.ruoyi.factorydata.mapper.ProductionLineDataMapper;
import com.ruoyi.factorydata.mapper.StationDataMapper;
import com.ruoyi.factorydata.mapper.WorkshopDataMapper;
import com.ruoyi.factorydata.service.IFactoryDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;


/**
 * 工厂建模信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-22
 */
@Slf4j
@Service
public class FactoryDataServiceImpl extends ServiceImpl<FactoryDataMapper, FactoryData> implements IFactoryDataService {
    @Autowired
    private FactoryDataMapper factoryDataMapper;

    @Autowired
    private WorkshopDataMapper workshopDataMapper;

    @Autowired
    private ProductionLineDataMapper productionLineDataMapper;

    @Autowired
    private StationDataMapper stationDataMapper;

    /**
     * 查询工厂建模信息
     *
     * @param id 工厂建模信息主键
     * @return 工厂建模信息
     */
    @Override
    public FactoryData selectFactoryDataById(Long id) {
        return factoryDataMapper.selectFactoryDataById(id);
    }

    /**
     * 查询工厂建模信息列表
     *
     * @param factoryDataDTO 工厂建模信息
     * @return 工厂建模信息
     */
    @Override
    public List<FactoryDataVo> selectFactoryDataList(FactoryDataDTO factoryDataDTO) {
//        WorkshopData workshopData = new WorkshopData();
        // 若工厂id不为空，则查询该工厂下的车间
//        if (factoryDataDTO != null && factoryDataDTO.getId() != null){
//            workshopData.setFactoryId(factoryDataDTO.getId());
//            workshopData.setName(factoryDataDTO.getWorkShopName());
//            workshopData.setWorkshopCode(factoryDataDTO.getWorkShopCode());
//            List<WorkshopData> workshopDataList = workshopDataMapper.selectWorkshopDataList(workshopData);
//            List<FactoryDataVo.FactoryDataVoBuilder> factoryDataVos = workshopDataList.stream().map(workshop -> {
//                FactoryData factoryDataById = factoryDataMapper.selectFactoryDataById(workshop.getFactoryId());
//                return FactoryDataVo.builder()
//                        .id(workshop.getId())
//                        .factoryName(factoryDataById.getFactoryName())
//                        .factoryCode(factoryDataById.getFactoryCode())
//                        .location(factoryDataById.getLocation())
//                        .remarks(workshop.getRemarks())
//                        .delFlag(workshop.getDelFlag())
//                        .version(workshop.getVersion())
//                        .workshopId(workshop.getId())
//                        .workshopName(workshop.getName())
//                        .workshopCode(workshop.getWorkshopCode())
//                        .createBy(workshop.getCreateBy())
//                        .createTime(workshop.getCreateTime())
//                        .updateTime(workshop.getUpdateTime());
//            }).collect(Collectors.toList());
//            return factoryDataVos.stream().map(FactoryDataVo.FactoryDataVoBuilder::build).collect(Collectors.toList());
//        }
        // 查询所有的工厂
        assert factoryDataDTO != null;
        log.info("查询工厂列表：{}", factoryDataDTO);
        QueryWrapper<FactoryData> factoryDataQueryWrapper = new QueryWrapper<>();
        factoryDataQueryWrapper.lambda()
                .like(factoryDataDTO.getFactoryName() != null && !factoryDataDTO.getFactoryName().isBlank(), FactoryData::getFactoryName, factoryDataDTO.getFactoryName())
                .like(factoryDataDTO.getFactoryCode() != null && !factoryDataDTO.getFactoryCode().isBlank(), FactoryData::getFactoryCode, factoryDataDTO.getFactoryCode());
        List<FactoryData> factoryDataList = factoryDataMapper.selectList(factoryDataQueryWrapper);
//        FactoryData factoryData = new FactoryData();
//        factoryData.setFactoryName(factoryDataDTO.getFactoryName());
//        factoryData.setFactoryCode(factoryDataDTO.getFactoryCode());
//        List<FactoryData> factoryDataList = factoryDataMapper.selectFactoryDataList(factoryData);
      List<FactoryDataVo> factoryDataVos  = factoryDataList.stream().map(factory -> {
            return FactoryDataVo.builder()
                    .id(factory.getId())
                    .factoryName(factory.getFactoryName())
                    .factoryCode(factory.getFactoryCode())
                    .location(factory.getLocation())
                    .remarks(factory.getRemarks())
                    .delFlag(factory.getDelFlag())
                    .version(factory.getVersion())
                    .createBy(factory.getCreateBy())
                    .createTime(factory.getCreateTime())
                    .updateTime(factory.getUpdateTime());
        }).map(FactoryDataVo.FactoryDataVoBuilder::build).collect(Collectors.toList());
        Page<FactoryData> queryData=(Page<FactoryData>)factoryDataList;
        Page<FactoryDataVo> page = new Page<>(queryData.getPageNum(), queryData.getPageSize());
        page.setTotal(queryData.getTotal());
        page.addAll(factoryDataVos);
        return page;
    }

    @Override
    public List<FactoryTreeVo> selectFactoryTreeList(FactoryData factoryData) {
        //查询所有的工厂
        List<FactoryTreeVo> root = new ArrayList<>();
        List<FactoryData> factoryDataList = factoryDataMapper.selectFactoryDataList(factoryData);
        // 使用AtomicLong确保线程安全的唯一递增ID (从1开始)
        AtomicLong nodeId = new AtomicLong(1);
        if (factoryDataList != null && factoryDataList.size() > 0){
            List<FactoryTreeVo.FactoryTreeVoBuilder> collect = factoryDataList.stream().map(factory -> {
                // 工厂节点ID
                long factoryNodeId = nodeId.getAndIncrement();
                WorkshopData workshopData = new WorkshopData();
                workshopData.setFactoryId(factory.getId());
                //查询工厂下的车间
                List<WorkshopData> workshopDataList = workshopDataMapper.selectWorkshopDataList(workshopData);
                List<FactoryTreeVo.FactoryTreeVoBuilder> workshopDatas = workshopDataList.stream().map(workshop -> {
                    // 车间节点ID
                    long workshopNodeId = nodeId.getAndIncrement();
                    ProductionLineData productionLineData = new ProductionLineData();
                    productionLineData.setWorkshopId(workshop.getId());
                    // 查询车间下的产线
                    List<ProductionLineData> productionLineDataList = productionLineDataMapper.selectProductionLineDataList(productionLineData);
                    List<FactoryTreeVo.FactoryTreeVoBuilder> productionDatas = productionLineDataList.stream().map(productionLine -> {
                        // 产线节点ID
                        long productionLineNodeId = nodeId.getAndIncrement();
                        StationData stationData = new StationData();
                        stationData.setProductionLineId(productionLine.getId());
                        // 查询产线下的工位
                        List<StationData> stationDataList = stationDataMapper.selectStationDataList(stationData);
//                        List<FactoryTreeVo> station1 = stationDataList.stream().map(station -> {
//                            return FactoryTreeVo.builder()
//                                    .id(station.getId())
//                                    .name(station.getName())
//                                    .parentId(station.getId())
//                                    .type("station")
//                                    .build();
//                        }).collect(Collectors.toList());
                        return FactoryTreeVo.builder()
                                .id(productionLine.getId())
                                .nodeId(productionLineNodeId)
                                .name(productionLine.getName())
                                .parentId(productionLine.getId())
                                .type("productionLine")
                                .children(null);
                    }).collect(Collectors.toList());
                    List<FactoryTreeVo> productionDatas1 = productionDatas.stream().map(FactoryTreeVo.FactoryTreeVoBuilder::build).collect(Collectors.toList());
                    return FactoryTreeVo.builder()
                            .id(workshop.getId())
                            .nodeId(workshopNodeId)
                            .name(workshop.getName())
                            .parentId(factory.getId())
                            .type("workshop")
                            .children(productionDatas1);
                }).collect(Collectors.toList());
                List<FactoryTreeVo> children = workshopDatas.stream().map(FactoryTreeVo.FactoryTreeVoBuilder::build).collect(Collectors.toList());
                return FactoryTreeVo.builder()
                        .id(factory.getId())
                        .nodeId(factoryNodeId)
                        .name(factory.getFactoryName())
                        .parentId(0L)
                        .type("factory")
                        .children(children);
            }).collect(Collectors.toList());
            List<FactoryTreeVo> factoryTreeVos = collect.stream().map(FactoryTreeVo.FactoryTreeVoBuilder::build).collect(Collectors.toList());
            FactoryTreeVo.FactoryTreeVoBuilder children = FactoryTreeVo.builder()
                    .id(0L)
                    .nodeId(0L)
                    .name("全部")
                    .parentId(null)
                    .type("root")
                    .children(factoryTreeVos);
            root.add(children.build());
            return root;
        }
        return null;
    }

    /**
     * 新增工厂建模信息
     *
     * @param factoryData 工厂建模信息
     * @return 结果
     */
    @Override
    public int insertFactoryData(FactoryData factoryData) {
            factoryData.setCreateTime(DateUtils.getNowDate());
            return factoryDataMapper.insertFactoryData(factoryData);
    }

    /**
     * 修改工厂建模信息
     *
     * @param factoryData 工厂建模信息
     * @return 结果
     */
    @Override
    public int updateFactoryData(FactoryData factoryData) {
                factoryData.setUpdateTime(DateUtils.getNowDate());
        return factoryDataMapper.updateFactoryData(factoryData);
    }

    /**
     * 批量删除工厂建模信息
     *
     * @param ids 需要删除的工厂建模信息主键
     * @return 结果
     */
    @Override
    public int deleteFactoryDataByIds(Long[] ids) {
        int i = factoryDataMapper.deleteBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
        return i;
    }

    /**
     * 删除工厂建模信息信息
     *
     * @param id 工厂建模信息主键
     * @return 结果
     */
    @Override
    public int deleteFactoryDataById(Long id) {
        return factoryDataMapper.deleteFactoryDataById(id);
    }
}